<?php

namespace app\admins\controller;

use app\admins\model\Admin;
use app\BaseController;

class Account extends BaseController
{
    protected $model;

    // 初始化
    protected function initialize()
    {
        $this->model = new Admin();
    }

    // 登录
    public function login()
    {
        return $this->app->view->fetch();
    }

    // 登录验证
    public function dologin()
    {
        // 验证
        $rule = [
            'username|用户名' => 'require|chsDash|min:3|max:25|token',
            'password|密码' => 'require|min:5|max:30',
            'captcha|验证码' => 'require|captcha'
        ];
        $post = $this->request->post();
        $validate = $this->app->validate->rule($rule);
        if (!$validate->check($post)) {
            return json(['code' => 1, 'msg' => $validate->getError()]);
        }

        // 校验用户
        $auth = $this->model->where('username', $post['username'])->find();
        if (!$auth) {
            return json(['code' => 1, 'msg' => '用户不存在']);
        }
        if (!password_verify($post['password'], $auth['password'])) {
            return json(['code' => 1, 'msg' => '密码错误']);
        }
        if ($auth['status']) {
            return json(['code' => 1, 'msg' => '该用户已禁用，请联系管理员']);
        }

        // 会话存储
        if (!session_id()) session_start();
        $this->app->session->set('auth', $auth);

        // 永久登录
        $salt = rand(100000, 999999);
        $token = md5($salt . $auth['username'] . $salt);
        if (!empty($post['remember'])) {
            $this->app->cookie->forever('auth', $token);
            $this->model->where('id', $auth['id'])->update(['remember_token' => $token]);
        } else {
            $this->model->where('id', $auth['id'])->update(['remember_token' => '']);
        }

        // 单点登录
        $randstr = md5($salt . $token . $salt);
        $this->app->cache->set('rand' . $auth['id'], $randstr);
        $this->app->cookie->set('randstr', $randstr);

        // 登录成功
        $this->model->where('id', $auth['id'])->update(['lastlogin' => time()]);
        return json(['code' => 0, 'msg' => '登录成功']);
    }

    // 退出登录
    public function logout()
    {
        $this->app->session->delete('auth');
        $this->app->cookie->delete('auth');
        // 跳转到登录页面
        return json(['code' => 0, 'msg' => '登出成功']);
    }

    // 修改资料
    public function profile()
    {
        $auth = $this->app->session->get('auth');
        if (!$auth) return json(['code' => 1, 'msg' => '请先登录']);
        $row = $this->model->where('id', $auth['id'])->find();
        if ($this->request->isAjax()) {
            $param = $this->request->post();
            try {
                $this->validate($param, [
                    '__token__' => 'require|token',
                    'password|密码' => 'requireWith:password|min:5',
                    'realname|真实姓名' => 'require|chsAlpha',
                    'avatar|图像' => 'requireWith:avatar|regex:/\/storage\/.+?\./i',
                ]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            $data = $this->request->only(['password', 'realname', 'avatar']);
            if (empty($data['password'])) {
                unset($data['password']);
            } else {
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }
            if ($param['username'] == 'admin') unset($data['password']); // admin示例不改
            $row->save($data);
            $avatar = $data['avatar'] ?? '';
            $avatar && $this->app->db->table('files')->where('path', $avatar)->update(['status' => 0]);
            return json(['code' => 0, 'msg' => '修改成功']);
            exit;
        }
        $this->app->view->assign(['row' => $row]);
        return $this->app->view->fetch();
    }

    // 清除缓存
    public function clear()
    {
        $this->app->cache->clear();
        $runtime_path = $this->app->getRuntimePath();
        if ($this->delete_dir_file($runtime_path)) {
            return json(['code' => 0, 'msg' => '清除成功']);
        } else {
            return json(['code' => 1, 'msg' => '清除失败']);
        }
    }

    // 清除缓存目录文件
    private function delete_dir_file($dir)
    {
        //声明一个初始状态 默认情况下缓存未被删除
        $res = false;
        if (is_dir($dir)) {
            //成功打开目录流
            if ($handle = opendir($dir)) {
                while (($file = readdir($handle)) !== false) {
                    if ($file != '.' && $file != '..') {
                        //目录只有为空的情况下才能被直接删除
                        if (is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
                            $this->delete_dir_file($dir . DIRECTORY_SEPARATOR . $file);
                        } else {
                            //unlink只能删除一个文件
                            unlink($dir . DIRECTORY_SEPARATOR . $file);
                        }
                    }
                }
            }
            //关闭目录句柄
            closedir($handle);
            if (rmdir($dir)) {
                $res = true;
            }
        }
        return $res;
    }
}
